var Chat = {};
socket = null;
Chat.initialize = function (userId) {

    // if(!userId){
    //     console.log("用户名不能为空！");
    //     return;
    // }
    debugger;
    socket = io.connect('http://localhost:8888/chat');
    socket.on('connect', function () {
        console.log("成功连接服务端！");
    });
    socket.on('robot', function (data) {
        var message = JSON.stringify(data);
        console.log(message);
        output('<span class="username-msg">收到服务端消息 </span>  ' + data.message);
    });
    socket.on('chatP2P', function (data) {
        var jsonMsg = JSON.stringify(data);
        console.log(jsonMsg);
        if ($("#name").val() !== data.userName)
            output('<span class="username-msg">收到来自用户  ' + data.from + ':</span> ' + data.message);
    });

    socket.on('chatGroup', function (data) {
        var jsonMsg = JSON.stringify(data);
        console.log(jsonMsg);
        if ($("#name").val() !== data.userName)
            output('<span class="username-msg">收到群聊  用户' + data.userName + ':</span> ' + data.message);
    });
    socket.on('disconnect', function () {
        output('<span class="disconnect-msg">The client has disconnected!</span>');
    });
};


Chat.sendDisconnect = function () {
    if (!socket) {
        console.log("还未连接服务端！");
        return;
    }
    socket.disconnect();
};
Chat.sendGroupMessage = function () {
    if (!socket) {
        console.log("请先连接服务端！");
        return;
    }
    var userName = $("#name").val();
    var message = $('#msg').val();
    if(!message){
        console.log("发送内容不能为空！");
        return;
    }
    $('#msg').val('');
    output('<span class="username-msg">用户  ' + userName + "发送了:  " + message + '</span> ');
    socket.emit('chatGroup', {userName: userName, message: message});
};

Chat.sendP2PMessage = function () {
    if (!socket) {
        console.log("请先连接服务端！");
        return;
    }
    var userName = $("#name").val();
    var message = $('#msg').val();
    if(!message){
        console.log("发送内容不能为空！");
        return;
    }
    var to = $('#to').val();
    if(!to){
        console.log("消息接收者不能为空！");
        return;
    }
    $('#msg').val('');
    output('<span class="username-msg">用户 ' + userName + "发送了     " + message + ':</span> ');
    socket.emit('chatP2P', {from: userName, message: message, to: to});
};

function output(message) {
    var currentTime = "<span class='time'>" + new Date() + "</span>";
    var element = $("<div>" + currentTime + " " + message + "</div>");
    $('#console').append(element);
}